# 创建数组

# 空数组
arr1 = []
arr2 = Array.new

# 带初始值的数组
arr3 = [1, 2, 3]
arr4 = %w[apple banana orange] # 字符串数组简写

# 使用范围创建
arr5 = (1..5).to_a # [1, 2, 3, 4, 5]

# 使用Array.new创建
arr6 = Array.new(3) # [nil, nil, nil]
arr7 = Array.new(3, "ruby") # ["ruby", "ruby", "ruby"]

fruits = ["apple", "banana", "orange"]

puts fruits[0]    # "apple" (正向索引)
puts fruits[-1]   # "orange" (负向索引)
puts fruits[1..2] # ["banana", "orange"] (范围)
puts fruits.first # "apple"
puts fruits.last  # "orange"

puts "============================"

arr = [1, 2]

# 添加
arr.push(3)     # [1, 2, 3]
arr << 4        # [1, 2, 3, 4] (同push)
arr.unshift(0)  # [0, 1, 2, 3, 4] (添加到开头)

# 删除
arr.pop         # 移除并返回最后一个元素 (4)
arr.shift       # 移除并返回第一个元素 (0)
arr.delete(2)   # 删除指定元素 [1, 3]

puts "============================"

a = [1, 2, 3]
b = [3, 4, 5]

# 合并数组 (去重)
puts a | b      # [1, 2, 3, 4, 5]

# 交集
puts a & b      # [3]

# 差集
puts a - b      # [1, 2]

# 连接
puts a + b      # [1, 2, 3, 3, 4, 5]

puts "============================"

numbers = [1, 2, 3]

# 遍历
numbers.each { |n| puts n * 2 }

# 映射新数组
doubled = numbers.map { |n| n * 2 } # [2, 4, 6]
puts "doubled: #{doubled}" # 输出：doubled: [2, 4, 6]

# 筛选
evens = numbers.select { |n| n.even? } # [2]
puts "evens: #{evens}" # 输出 evens: [2]

# 排序
sorted = [3, 1, 2].sort # [1, 2, 3]
puts "sorted: #{sorted}" # 输出 sorted: [1, 2, 3]